<?php
namespace app\before\controller;

class Upgrade extends Base
{
    private $tn = 'upgrade';

    public function index()
    {
        if (isset($this->get['page']) && isset($this->get['limit'])) {
            $where = [];
            $where['u.from_city'] = ['in',$this->admin_area];
            //购买人
            if(isset($this->get['user_id'])){
                $where['user_id'] = $this->get['user_id'];
            }
            //购买时间
            if(isset($this->get['date'])){
                $where['pay_time'] = [['egt',strtotime($this->get['date'])],['lt',strtotime($this->get['date'].'+1 day')]];
            }
            $list  = db($this->tn)->alias('b')->join(['bz_user' => 'u'],'u.id = b.user_id')->field('b.*,FROM_UNIXTIME(b.pay_time,"%Y-%m-%d %H:%i") as pay_time,number')->where($where)->order('id', 'desc')->page($this->get['page'])->limit($this->get['limit'])->select();
            foreach ($list as $k => $v) {
            }
            $count = db($this->tn)->alias('b')->join(['bz_user' => 'u'],'u.id = b.user_id')->field('b.*')->where($where)->count();
            $this->returnAPI('', 0, $list, ['count' => $count, 'limit' => $this->get['limit']]);
        }
        return $this->fetch();
    }

    public function edit($id = 0)
    {
        $model = model($this->tn);
        if ($this->post) {
            if ($id) {
                $model = $model->get($id);
                if (is_null($model)) {
                    $this->returnAPI('信息有误,请稍后重试');
                }
            }
            $result = $model->validate($this->tn)->allowField(true)->save($this->post);
            if ($result !== false) {
                $this->returnAPI('操作成功', 0);
            }
            $this->returnAPI($model->getError());
        }
        $model = $model->get($id);
        if (is_null($model)) {
            $data = $this->table_fields($this->tn);
        } else {
            $data = $model->getData();
        }
        return $this->fetch('', ['data' => $data]);
    }
}
